const Like = require('../models/Like')
const Article = require('../models/Article')
exports.postLike = async (req, res, next) => {
  const articleId = req.params.articleId
  console.log('articleId: ', articleId)
  const userId = req._id
  console.log('userId: ', userId)
  try {
    const likeExists = await Like.findOne({
      userId,
      articleId,
    })
    console.log('likeExists: ', likeExists)
    if (likeExists) {
      // 如果点赞已存在，执行取消点赞逻辑
      await Like.deleteOne({ _id: likeExists._id })
      await Article.updateOne({ _id: articleId }, { $inc: { like_num: -1 } })
      res.success({ like: 0 }, '取消点赞成功')
    } else {
      // 如果点赞不存在，执行点赞逻辑
      const newLike = new Like({
        userId,
        articleId,
      })
      await newLike.save()
      await Article.updateOne({ _id: articleId }, { $inc: { like_num: 1 } })
      res.success({ like: 1 }, '点赞成功')
    }
  } catch (error) {
    next(error)
  }
}
